/**
 * <p>Title: AuditTrialMetadataDaoImpl</p>
 * <p>Description: The implementation of AuditTrialMetadataDao</p>
 * <p>Copyright: Shanghai Batchsight Pharmaceutical Technologies, Inc. Copyright(c) 2016</p>
 * @author Wan Shuaishuai
 * @version 1.0
 * <pre>Histroy:
 *       2016-10-10  Wan Shuaishuai  Create
 *</pre>
*/
package cn.jhg.account.dao;

import javax.annotation.Resource;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

import cn.jhg.account.dao.AuditTrailMetadataDao;
import cn.jhg.account.entity.AuditTrailMetadata;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

/**
 * 审计追踪元数据 DAO实现
 * @author Wan Shuaishuai
 *
 */
@Repository 
public class AuditTrailMetadataDaoImpl implements AuditTrailMetadataDao {
	
	private Logger logger=LoggerFactory.getLogger(AuditTrailMetadataDaoImpl.class);
	
	@Resource
	private MongoTemplate mongoTemplate;
	/**
	 * 增加元数据
	 * <p>Description:使用传入的 id 将 metadata 增加到 ibcp 库  audit_trail_metadata 表中<p>
	 * @param id  
	 * @param metadata  元数据
	 * @return 219376226 & 0   ErrorCode  
	 */
	public int addMetadata(ObjectId id, Document metadata) {
		try{
			DBObject object = new BasicDBObject();//设置需要插入到数据库的文档对象
			object.put("_id", id);
			object.put("metadate", metadata);
			mongoTemplate.insert(object,"audit_trail_metadata");
			logger.info("[INF221710593] 添加元数据成功");
			return 0;//元数据添加成功
		}catch(Exception e){
			logger.error("[ERR219564009]添加元数据失败",e.getMessage());
			return 219564009;//异常错误代码
		}
	}
	
	/**
	 * 查询元数据
	 * @param id  
	 * @return doc  元数据、错误代码
	 */
	public Document queryMetadata(ObjectId id) {
		Document doc = new Document();
		try{	
			AuditTrailMetadata data = mongoTemplate.findById(id, AuditTrailMetadata.class, "audit_trail_metadata");
			if(data==null){
				doc.append("ErrorCode", 219546624);//id不存在，查询元数据失败
				logger.error("[ERR219546624] ID不存在,查询元数据失败");
			}else{			
				doc.append("metadata", data.getMetadata());
				doc.append("ErrorCode", 0);
				logger.info("[INF221723714] 查询元数据成功");
			}
			return doc;
		}catch(Exception e){
			logger.error("[ERR219564012]查询元数据失败",e.getMessage());
			doc.append("ErrorCode", 219564012);//异常错误代码
			return doc;
		}
	}
}
